<!--
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-31 11:39:05
 * @LastEditors: jhw
 * @Description: 文件描述
-->
<template>
  <div>
    <button @click="exportExcel(100)">导出 Excel在1000左右</button>
    <br />
    <button @click="exportExcel(10000)">导出 Excel在1W左右</button>
    <p v-if="exportStatus === 'processing'">正在生成文件...</p>
    <p v-if="exportStatus === 'success'" style="color: green">导出成功！</p>
    <p v-if="exportStatus === 'error'" style="color: red">导出失败</p>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { exportData } from './export'

const exportStatus = ref('')

const exportExcel = (num: number) => {
  exportStatus.value = 'processing'

  // 创建 Web Worker
  const worker = new Worker(new URL('@/workers/excel.js', import.meta.url), {
    type: 'module',
  })

  worker.postMessage({
    data: exportData(num),
    fileName: '用户数据.xlsx',
  })

  worker.onmessage = (e) => {
    if (e.data.status === 'success') {
      // 从 ArrayBuffer 重建 Uint8Array
      const buffer = new Uint8Array(e.data.arrayBuffer)
      // 创建 Blob 并下载
      const blob = new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })

      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = e.data.fileName
      link.click()

      exportStatus.value = 'success'
    } else {
      console.error('导出失败:', e.data.error)
      exportStatus.value = 'error'
    }
    worker.terminate()
  }

  worker.onerror = (error) => {
    console.error('Worker 错误:', error)
    exportStatus.value = 'error'
    worker.terminate()
  }
}
</script>
